package com.zhou.util;

import org.apache.commons.io.IOUtils;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;

import java.io.*;

/**
 * @author lang.zhou
 * @date 2019/12/18
 */
public class SerializeUtil implements RedisSerializer<Object> {

    //序列化
    public static byte [] write(Object obj) throws IOException{
        ObjectOutputStream obi = null;
        ByteArrayOutputStream bai = null;
        try {
            bai=new ByteArrayOutputStream();
            obi=new ObjectOutputStream(bai);
            obi.writeObject(obj);
            return bai.toByteArray();
        } finally {
            IOUtils.closeQuietly(obi);
            IOUtils.closeQuietly(bai);
        }
    }

    //反序列化
    public static Object read(byte[] byt) throws Exception{
        ObjectInputStream oii=null;
        ByteArrayInputStream bis=null;

        try {
            bis=new ByteArrayInputStream(byt);
            oii=new ObjectInputStream(bis);
            return oii.readObject();
        } finally {
            IOUtils.closeQuietly(oii);
            IOUtils.closeQuietly(bis);
        }
    }
    public static void write(Object o,File file) throws IOException{

        OutputStream out = null;
        try {
            out = new FileOutputStream(file);
            write(o,out);
        } finally {
            IOUtils.closeQuietly(out);
        }
    }
    public static void write(Object o,OutputStream out) throws IOException {

        ObjectOutputStream oos = null;
        try {
            oos = new ObjectOutputStream(out);
            oos.writeObject(o);
            oos.flush();
        } finally {
            IOUtils.closeQuietly(oos);
        }
    }
    public static Object read(InputStream in) throws Exception {
        ObjectInputStream ois = null;
        try {
            ois = new ObjectInputStream(in);
            return ois.readObject();
        } finally {
            IOUtils.closeQuietly(ois);
        }
    }
    public static Object read(File file) throws Exception {
        InputStream in = null;
        try {
            in = new FileInputStream(file);
            return read(in);
        } finally {
            IOUtils.closeQuietly(in);
        }
    }


    @Override
    public byte[] serialize(Object o) throws SerializationException {

        try {
            return write(o);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Object deserialize(byte[] bytes) throws SerializationException {
        try {
            return read(bytes);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
